package ui.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.wyz.troika_test.R;

import butterknife.BindView;
import presenter.MainPresenter;
import ui.adapter.MainRecyclerAdapter;
import ui.fragment.EnsureResetBTFragment;
import ui.view.IMainView;

import static presenter.MainPresenter.REQUEST_CONNECT_DEVICE_INSECURE;
import static presenter.MainPresenter.REQUEST_CONNECT_DEVICE_SECURE;
import static presenter.MainPresenter.REQUEST_ENABLE_BT;

public class MainActivity extends BaseActivity<MainPresenter>
        implements IMainView, NavigationView.OnNavigationItemSelectedListener,
        View.OnClickListener, MainRecyclerAdapter.OnMainListClickListener,
        EnsureResetBTFragment.OnDialogCallBack{
    
    @BindView(R.id.drawer_layout) protected DrawerLayout mDrawerLayout;
    @BindView(R.id.nav_view) protected NavigationView mNavigationView;
    @BindView(R.id.collapsing_layout) protected CollapsingToolbarLayout mCollapsingLayout;
    //@BindView(R.id.tv_data_test) protected TextView showDataView;
    @BindView(R.id.m_fab_menu) protected FloatingActionsMenu mFabMenu;
    @BindView(R.id.m_fab_remote) protected FloatingActionButton mRemoteBtn;
    @BindView(R.id.m_fab_bluetooth) protected FloatingActionButton mBlueBtn;
    @BindView(R.id.main_recycler_view) protected RecyclerView mRecyclerView;
    @BindView(R.id.tv_main_state) protected TextView mStateTx;
    @BindView(R.id.img_main_state_icon) protected ImageView mStateIc;
    
    private MainRecyclerAdapter mAdapter;
    private BTStateReceiver btStateReceiver;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //showDataView.setText("init");
        mPresenter.fillData();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(btStateReceiver);
    }
    
    @Override
    protected void init() {
        super.init();
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar,
                                          R.string.navigation_drawer_open,
                                          R.string.navigation_drawer_close);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        mNavigationView.setNavigationItemSelectedListener(this);
        mAdapter = new MainRecyclerAdapter(this);//test used
        mAdapter.setListener(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mRecyclerView.setAdapter(mAdapter);
        mBlueBtn.setOnClickListener(this);
    
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        btStateReceiver = new BTStateReceiver();
        registerReceiver(btStateReceiver, filter);
    }
    
    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }
    
    @Override
    public void initPresenter() {
        this.mPresenter = new MainPresenter(this);
    }
    
    @Override
    public void fillData(String data) {
        //mStateTx.setText(data);
    }
    
    @Override
    public void refreshData(String data) {
        mStateTx.setText(data);//test used
        //mAdapter.updateDate();//更新recyclerView数据
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.secure_connect_scan:
                mPresenter.startScanActivity(REQUEST_CONNECT_DEVICE_SECURE);
                break;
            case R.id.insecure_connect_scan:
                mPresenter.startScanActivity(REQUEST_CONNECT_DEVICE_INSECURE);
                break;
            case R.id.discoverable:
                mPresenter.ensureDiscoverable();
                break;
            default:
                break;
        }
        return true;
    }
    
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
    
        if (id == R.id.nav_summery) {
            // Handle the camera action
        } else if (id == R.id.nav_advice) {
            Intent intent = new Intent(this, AdviceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_setting) {
        
        }
        
        mDrawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE_SECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    mPresenter.connectDevice(data, true);
                }
                break;
            case REQUEST_CONNECT_DEVICE_INSECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    mPresenter.connectDevice(data, false);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    mPresenter.setBTState(true);
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d("MainActivity", "BT not enabled");
                    
                }
        }
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.m_fab_remote:
                break;
            case R.id.m_fab_bluetooth:
                mFabMenu.collapse();
                mPresenter.startBTService();
                break;
            default:
                break;
        }
    }
    
    @Override
    public void onItemClick(int position) {
        Toast.makeText(this, "click:"+position, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onSureReset(boolean isSure) {
        mPresenter.resetBTState();
    }
    
    
    private class BTStateReceiver extends BroadcastReceiver {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0) == BluetoothAdapter.STATE_OFF){
                Toast.makeText(context, "system bt service turn off!", Toast.LENGTH_SHORT).show();
                mPresenter.setBTState(false);
            }
        }
    }
}
